package com.example.redissontest.aop;

import com.example.redissontest.annotation.RepeatSubmitToken;
import com.example.redissontest.util.RedissonLockUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author rfuser
 */
@Aspect
@Component
@Slf4j
public class RepeatSubmitAspect {

    @Resource
    private RedissonLockUtil redissonLockUtil;


    @Around("@annotation(repeatSubmitToken)")
    public Object around(ProceedingJoinPoint point, RepeatSubmitToken repeatSubmitToken) throws Throwable {

        Object[] args = point.getArgs();
        String key = repeatSubmitToken.value();
        for (Object arg : args) {
            if (arg instanceof String) {
                key = key+"_"+arg;
                log.info("key:{}",key);
                break;
            }
        }

        boolean exists = redissonLockUtil.tryLock(key, repeatSubmitToken.waitTime(),
                repeatSubmitToken.leaseTime(), TimeUnit.SECONDS);
        if (!exists) {
            throw new RuntimeException("请勿重复提交");
        }
        try {
            return point.proceed();
        } finally {
            redissonLockUtil.unlock(repeatSubmitToken.value());
        }
    }
}
